//
//  SXTwoViewController.m
//  SXDataManager_Example
//
//  Created by wangshuixin on 2019/1/23.
//  Copyright © 2019 wangshuixin. All rights reserved.
//

#import "SXTwoViewController.h"
#import "SXDataManager-umbrella.h"
#import "AFNetworking.h"

@interface SXTwoViewController ()
@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UITextField *inputTF;
@property (strong, nonatomic) NSString *captchaId;
@end

@implementation SXTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 70, 40)];
    self.imageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.imageView];
    UIButton *fetchBtn = [[UIButton alloc] initWithFrame:CGRectMake(190, 100, 50, 40)];
    [fetchBtn setTitle:@"获取" forState:UIControlStateNormal];
    [fetchBtn addTarget:self action:@selector(getCaptcha) forControlEvents:UIControlEventTouchUpInside];
    fetchBtn.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:fetchBtn];
    self.inputTF = [[UITextField alloc] initWithFrame:CGRectMake(100, 160, 100, 30)];
    self.inputTF.placeholder = @"请输入验证码";
    self.inputTF.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.inputTF];
    UIButton *verifyBtn = [[UIButton alloc] initWithFrame:CGRectMake(220, 160, 50, 30)];
    [verifyBtn setTitle:@"验证" forState:UIControlStateNormal];
    [verifyBtn addTarget:self action:@selector(verifyCaptcha) forControlEvents:UIControlEventTouchUpInside];
    verifyBtn.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:verifyBtn];
}
-(void)viewWillAppear:(BOOL)animated {
    [self getCaptcha];
}

- (void)getCaptcha {
    NSDictionary *params = @{@"password":@"123456", @"username":@"qqas", @"sxx":@"ccccd", @"captchaType":@"character1", @"Id":@"0000", @"VerifyValue":@"aaaa"};
    __weak typeof(self) weakSelf = self;
    [SXTwoViewController PostDataWithPath:@"http://192.168.1.4:8080/api/getCaptcha" parameters:params progress:^(NSProgress *downloadProgress) {
        
    } success:^(id obj) {
        NSLog(@"lang请求post返回数据：%@", obj);
        NSString *base64String = obj[@"data"][@"captchaData"];
        // 将base64字符串转为NSData
        NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
        // 将NSData转为UIImage
        UIImage *image = [UIImage imageWithData: decodeData];
        weakSelf.imageView.image = image;
        self.captchaId = obj[@"data"][@"captchaId"];
    } failure:^(NSError *error) {
        
    }];
}

- (void)verifyCaptcha {
    if (!self.captchaId) {
        return;
    }
    NSDictionary *params = @{@"password":@"123456", @"username":@"qqas", @"sxx":@"ccccd", @"captchaId":self.captchaId, @"captchaValue":self.inputTF.text};
    [SXTwoViewController PostDataWithPath:@"http://192.168.1.4:8080/api/verifyCaptcha" parameters:params progress:^(NSProgress *downloadProgress) {
        
    } success:^(id obj) {
        NSLog(@"验证码校验：%@", obj);
        [SXToast showToast:obj[@"data"][@"status"] duration:2 location:@"center"];
    } failure:^(NSError *error) {
        
    }];
}

static AFHTTPSessionManager *manager;
+ (AFHTTPSessionManager *)sharedHttpSessionManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 15.0;
    });
    
    return manager;
}

+ (void)PostDataWithPath:(NSString *)path
              parameters:(NSDictionary *)parameters
                progress:(void(^ __nullable)(NSProgress  *downloadProgress))download
                 success:(void(^)(id obj))success
                 failure:(void (^)(NSError *error))failure{
    
    AFHTTPSessionManager *manager = [self sharedHttpSessionManager];
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.validatesDomainName = NO;
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;
    
    //    [manager.securityPolicy setAllowInvalidCertificates:NO];
    //    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:
                                                        @"application/json",
                                                        @"text/html",
                                                        @"text/json",
                                                        @"text/javascript",
                                                        @"text/plain" ,nil];
    
    NSString *finalUrl = [NSString stringWithFormat:@"%@",path];
    
    [manager POST:finalUrl parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        if (download != nil) {
            download(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
}

@end
